package cn.jaychang.demo5.order.exception;

import cn.jaychang.demo5.common.model.Result;
import cn.jaychang.demo5.common.util.ResponseUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义熔断异常类
 */
@Slf4j  // log日志
@Configuration // 注入到spring容器中
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    @PostConstruct
    public void init() {
        System.out.println("CustomBlockExceptionHandler.init");
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.error("接口限流了", e);
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        ResponseUtil.result(response, new Result(1999, "接口限流了", null));
    }
}
